﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FACUI.BasicClass;
using System.IO;
using System.Threading;
using Steema.TeeChart.Styles;
using Steema.TeeChart;

namespace FACUI.frmDialog
{
    public partial class frmMain : Form
    {
        public frmMain( )
        {
            base.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true);
            InitializeComponent();
            CGlobal.GroupDic.Clear();
            BeforeLoad();
            InitChart();
            if (CGlobal.CurShowGroup != null)
            {
                propertyGrid1.SelectedObject = CGlobal.CurShowGroup;
            }
            propertyZone.SelectedObject = CGlobal.MonitoringZone;
            //接收传感器组数据  端口10002
            BasicClass.GetData getData = new BasicClass.GetData(10002);
            Thread th = new Thread(new ThreadStart(getData.ReceiveData));
            th.IsBackground = true;
            th.Start();
            //接收转发到9091转发的数据
            GetSource _udpSource = new GetSource(9091);
            Thread thsource = new Thread(new ThreadStart(_udpSource.ReceiveData));
            thsource.IsBackground = true;
            thsource.Start();
            //继电器控制板通信
            CSource.thMcuSendToCore = new Thread(CSource.tdtc.SendHeart);
            CSource.thMcuSendToCore.Start();
            CSource.thMcuSendToCore.IsBackground = true;
        }

        /// <summary>
        /// 错误信息显示时间间隔
        /// </summary>
        private const int iErrInfoDlg = 30;
        private DateTime dt = DateTime.Now;
        private frmTxt _frmTxt = new frmTxt();
        private CfgNode curstaCfg = null;
        private string lxcfgPath = "";
        //private Dictionary<string, StationCfg> statDic = new Dictionary<string, StationCfg>();

        private Point 视图上的offset;
        private Graphics g;
        private int m_HBarHeight;
        private int m_VBarWidth;
        private MapData mapData;

        private void SetQuDuanZhanYong(string strQuDuanName)
        {
            foreach (Quduan qd in CGlobal.DrawStrDic.Keys)
            {
                if (qd.name == strQuDuanName)
                {
                    Sharp.set显示模式(false);
                    this.mapData.区段变色笔(strQuDuanName, CGlobal.DifRed);
                }
            }
        }
        void timer_Tick(object sender, EventArgs e)
        {
            //SetQuDuanZhanYong(CGlobal.DrawStrDic.Keys.ElementAt(0).name);
            lblTime.Text = string.Format("待处理数据包：{0} 当前时间：{1}", CGlobal.GetWaitCount(), DateTime.Now);
            if (mapData == null) return;            
            if (!(mapData.allQuduan.Count > 0)) return;   
            
            //……
            int iPos = CGlobal.GetWaitCount() / 2;
            if (iPos < 1) iPos = 1;
            if (CGlobal.GetWaitCount() == 0) return;
            List<DGZone> tmp = new List<DGZone>();
            if (CGlobal.StrHostType == "6U")
            {
                CGlobal.unPackEx(iPos, ref tmp);
            }
            else
            {
                CGlobal.unPack(iPos, ref tmp);
            }
            if (tmp.Count <= 0) return;
            Sharp.set显示模式(false);
            int x = mapData.Rectxt.Left;
            int width = mapData.Rectxt.Width / mapData.iTxtColumnCount;
            
            foreach (DGZone zone in tmp)
            {                
                mapData.区段变色笔(zone.strName, zone.LightBlet);                
            }
            pMap.Invalidate();

            //修正显示数据
            if (CGlobal.CurDrawGroup == null)
            {
                CGlobal.CurDrawGroup = CGlobal.GroupDic[CGlobal.CurShowGroup.计轴点编号];
            }
            CGlobal.CurShowGroup = new 传感器分组(CGlobal.CurDrawGroup);
            propertyGrid1.SelectedObject = CGlobal.CurShowGroup;

            propertyZone.SelectedObject = CGlobal.MonitoringZone;
        }                                    
       
        protected override void OnClosed(EventArgs e)
        {
            Application.Exit();
        }
        
        /***************************************************************************************************************************/
        
        private void InitLized(CfgNode node, CfgNode root)
        {
            this.mapData = new MapData(node, root);
            this.mapData.loadNode();
            this.m_VBarWidth = 200;
            this.m_HBarHeight = 200;
            this.m_HBar.Maximum = this.m_HBarHeight;
            this.m_HBar.Minimum = 1;
            this.m_VBar.Maximum = this.m_VBarWidth;
            this.m_VBar.Minimum = 1;
            this.m_VBar.LargeChange = 10;
            this.m_VBar.SmallChange = 1;
            this.m_HBar.LargeChange = 10;
            this.m_HBar.SmallChange = 1;
            
            base.ResumeLayout(true);
            
            base.ClientSize = new Size(this.mapData.ct.mapsize.Width , this.mapData.ct.mapsize.Height );
            base.Size = new Size(base.Size.Width - this.m_VBar.Width, base.Size.Height - this.m_HBar.Height);
            this.mapData.resetGrid();           
            if (this.mapData.nodeRoot == null)
            {
                this.Text = "";
                base.Size = new Size(900, 700);
            }
            this.mapData.ReDoStack.isModified = false;
            foreach (GroupInfo gi in mapData.dicGroup.Values)
            {
                LxGroup lg = new LxGroup();
                lg.text = gi.strName;
                double wav = 0;
                if (double.TryParse(gi.strWav1, out wav))
                {
                    lg.sensor1.dblBase = wav;
                }
                if (double.TryParse(gi.strWav2, out wav))
                {
                    lg.sensor2.dblBase = wav;
                }
                CGlobal.GroupDic.Add(lg.text, lg);
            }
            List<JYJ> lstJyj = new List<JYJ>();
            foreach (Sharp s in this.mapData.allItems)
            {
                if (s.sharpType == "sbJYJ")
                {
                    lstJyj.Add((JYJ)s);
                }
            }
            for (int i = 0; i < lstJyj.Count; i++)
            {
                if (!CGlobal.GroupDic.ContainsKey(lstJyj[i].text))
                {
                    lstJyj.RemoveAt(i);
                    i--;
                }
            }
            CGlobal.DrawStrDic.Clear();
            foreach (Quduan qd in mapData.allQuduan) 
            {
                mapData.区段变色笔(qd.name, CGlobal.DifBasic);
                //保证区段为有效区段
                if (qd.name.Contains("G"))
                {
                    //查找有效区段内安装传感器的段
                    foreach (WCQD wcqd in qd.lst无岔区段)
                    {
                        Rectangle twc = new Rectangle(wcqd.pointX - 1, wcqd.pointY , wcqd.sizeDefineWidth + 1, wcqd.sizeDefineHeight );
                        foreach (JYJ jyj in lstJyj)
                        {
                            if (twc.Contains(jyj.point))
                            {
                                if (!CGlobal.DrawStrDic.ContainsKey(qd))
                                {
                                    CGlobal.DrawStrDic.Add(qd, new gState());
                                }
                                if (twc.Left+1 < jyj.pointX)
                                {
                                    if (!CGlobal.DrawStrDic[qd].cGroupR.Contains(jyj.text))
                                        CGlobal.DrawStrDic[qd].cGroupR.Add(jyj.text);
                                }
                                else
                                {
                                    if (!CGlobal.DrawStrDic[qd].cGroupL.Contains(jyj.text))
                                    {
                                        CGlobal.DrawStrDic[qd].mLeft = (CGlobal.DrawStrDic[qd].mLeft != 0) ? Math.Min(CGlobal.DrawStrDic[qd].mLeft, jyj.pointX) : jyj.pointX;
                                        CGlobal.DrawStrDic[qd].cGroupL.Add(jyj.text);
                                    }
                                }
                            }
                        }
                    }
                    foreach (DC dc in qd.lst道岔)
                    {
                        Rectangle tdc = new Rectangle(dc.pointX - 1, dc.pointY - 1, dc.sizeDefineWidth + 1, dc.sizeDefineHeight + 1);
                        foreach (JYJ jyj in lstJyj)
                        {
                            if (tdc.Contains(jyj.point))
                            {
                                if (!CGlobal.DrawStrDic.ContainsKey(qd))
                                {
                                    CGlobal.DrawStrDic.Add(qd, new gState());
                                }
                                if (tdc.Left+1 < jyj.pointX)
                                {
                                    if (!CGlobal.DrawStrDic[qd].cGroupR.Contains(jyj.text))
                                        CGlobal.DrawStrDic[qd].cGroupR.Add(jyj.text);
                                }
                                else
                                {
                                    if (!CGlobal.DrawStrDic[qd].cGroupL.Contains(jyj.text))
                                    {
                                        CGlobal.DrawStrDic[qd].mLeft = (CGlobal.DrawStrDic[qd].mLeft != 0) ? Math.Min(CGlobal.DrawStrDic[qd].mLeft, jyj.pointX) : jyj.pointX;
                                        CGlobal.DrawStrDic[qd].cGroupL.Add(jyj.text);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            List<Quduan> lstTmpQuDuan = new List<Quduan>();
            foreach (Quduan qd in CGlobal.DrawStrDic.Keys)
            {
                if (CGlobal.DrawStrDic[qd].cGroupL.Count < 1 || CGlobal.DrawStrDic[qd].cGroupR.Count < 1)
                {
                    lstTmpQuDuan.Add(qd);
                }
            }
            foreach (Quduan qd in lstTmpQuDuan)
            {
                CGlobal.DrawStrDic.Remove(qd);
            }
            if (CGlobal.GroupDic.Count >0)
            {
                CGlobal.CurShowGroup = new 传感器分组(CGlobal.GroupDic.Values.ToArray()[0]);
            }

            CGlobal.GroupDicAvgAxles.Clear();
            foreach (var item in CGlobal.GroupDic)
            {
                CGlobal.GroupDicAvgAxles.Add(item.Key,0);
            }
        }
        
        private void AddStatisticsNode(TreeNode trNode, Dictionary<string, CfgNode> cfgNode, string nodeName, string proKey)
        {
            if ((((trNode != null) && (cfgNode != null)) && !string.IsNullOrEmpty(nodeName)) && !string.IsNullOrEmpty(proKey))
            {
                TreeNode node = null;
                foreach (string str in cfgNode.Keys)
                {
                    node = new TreeNode(str);
                    if ((nodeName == "数据预览") && (cfgNode != null))
                    {
                        if (",devstate.ini,devcfg.ini,main.ini,Shebei.ini,Zh.ini,DC.ini,XHJ.ini,GD.ini,YP.ini,Quxian.ini,Baojing.ini,Digit.ini,Flcy.ini,HHcan.ini,SysCfg.ini,fenjitype.ini,".Contains("," + str + ","))
                        {
                            node.ImageIndex = 8;
                            node.SelectedImageIndex = 8;
                        }
                        else
                        {
                            node.ImageIndex = (cfgNode[str]["确认保存"] == "是") ? 8 : 6;
                            node.SelectedImageIndex = (cfgNode[str]["确认保存"] == "是") ? 8 : 6;
                        }
                    }
                    else
                    {
                        node.ImageIndex = 1;
                        node.SelectedImageIndex = 1;
                    }
                    node.Tag = cfgNode[str];
                    trNode.Nodes.Add(node);
                }
            }
        }

        public static List<string> GetLastOpenFile(ref string isStarthelp)
        {
            IniFile file = new IniFile(Application.StartupPath + @"\platform.dat");
            file.Load();
            isStarthelp = file.GetString("启动设置", "isStartHelp");
            List<string> list = new List<string>();
            if (file.GetString("启动设置", "isStartLastDate") != "否")
            {
                ICollection<string> sectionItemName = file.GetSectionItemName("RecentFile");
                if (sectionItemName != null)
                {
                    foreach (string str in sectionItemName)
                    {
                        list.Add(file.GetString("RecentFile", str));
                    }
                }
            }
            if (list.Count < 1)
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = "站场图|*.lxcfg";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    list.Add(ofd.FileName);
                }
            }
            return list;
        }

        public void OpenlxcfgFile(string fileName)
        {
            if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))
            {
                try
                {
                    curstaCfg = new CfgNode("")
                    {
                        NodeCfgFileName = fileName
                    };              
                    CfgNode.FromCfgFile(curstaCfg, fileName);
                    CfgNode subNode = curstaCfg.GetSubNode("_Global_Setting_");
                    if (subNode == null) return;
                    curstaCfg.NodeName = subNode["车站名称"];
                    if (!CfgManager.AddStationCfgNode(curstaCfg))
                    {
                        MessageBox.Show("已经打开了该站的配置", "打开文件");
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("文件格式错误！", "打开文件", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
            }
        }

        private void BeforeLoad()
        {
            try
            {
                string isStarthelp = "";
                List<string> lastOpenFile = GetLastOpenFile(ref isStarthelp);
                if (string.IsNullOrEmpty(this.lxcfgPath))
                {
                    foreach (string str3 in lastOpenFile)
                    {
                        this.OpenlxcfgFile(str3);
                    }
                }
                else
                {
                    this.OpenlxcfgFile(this.lxcfgPath);
                }
                InitLized(this.curstaCfg.GetSubNode("站场图"), this.curstaCfg);
                this.Text = "【" + this.curstaCfg.NodeName + "】 " + this.curstaCfg.GetSubNode("站场图").NodeName + " 基于光纤光栅技术的分路不良报警系统";

                System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
                timer.Interval = 200;
                timer.Tick += new EventHandler(timer_Tick);
                timer.Enabled = true;
                m_Basic.Click += new EventHandler(CheckPenClick);
                m_White.Click += new EventHandler(CheckPenClick);
                m_Red.Click += new EventHandler(CheckPenClick);
                m_Negative.Click += new EventHandler(CheckPenClick);
                pMap.Paint += new PaintEventHandler(pMap_Paint);
                pMap.MouseDoubleClick += new MouseEventHandler(pMap_MouseDoubleClick);
                pMap.MouseDown += new MouseEventHandler(pMap_MouseDown);
                pMap.Resize += new EventHandler(pMap_Resize);
                pMap.Click += new EventHandler(pMap_Click);
                pMap.MouseWheel += new MouseEventHandler(pMap_MouseWheel);
            }
            catch (Exception ex)
            { 
                System.Diagnostics.Debug.WriteLine(ex.StackTrace + ":" + ex.Message);
            }
        }

        void pMap_MouseWheel(object sender, MouseEventArgs e)
        {
            if ((Control.ModifierKeys == Keys.Control) || (this.mapData.selItems.Count == 0))
            {
                if (e.Delta > 0)
                {
                    this.视图上的offset.X = (int)((((double)((this.mapData.maxWorkArea.Width - this.mapData.ct.oraMapsize.Width) * this.mapData.scale)) / 2.0) - ((this.m_HBar.Value * ((this.mapData.maxWorkArea.Width * this.mapData.scale) - base.Size.Width)) / ((float)this.m_VBarWidth)));
                    this.视图上的offset.Y = (int)((((double)((this.mapData.maxWorkArea.Height - this.mapData.ct.oraMapsize.Height) * this.mapData.scale)) / 2.0) - ((this.m_VBar.Value * ((this.mapData.maxWorkArea.Height * this.mapData.scale) - (base.Size.Height - MapData.toolbarHeight))) / ((float)this.m_HBarHeight)));
                    this.mapData.scale *= 1.1f;
                    this.mapData.resetGrid();
                    pMap.Refresh();
                }
                else
                {
                    if ((((this.mapData.scale * this.mapData.ct.oraGridsize.Height) / 1.1f) >= 2f) && (((this.mapData.scale * this.mapData.ct.oraGridsize.Height) / 1.1f) >= 2f))
                    {
                        this.视图上的offset.X = (int)((((double)((this.mapData.maxWorkArea.Width - this.mapData.ct.oraMapsize.Width) * this.mapData.scale)) / 2.0) - ((this.m_HBar.Value * ((this.mapData.maxWorkArea.Width * this.mapData.scale) - base.Size.Width)) / ((float)this.m_VBarWidth)));
                        this.视图上的offset.Y = (int)((((double)((this.mapData.maxWorkArea.Height - this.mapData.ct.oraMapsize.Height) * this.mapData.scale)) / 2.0) - ((this.m_VBar.Value * ((this.mapData.maxWorkArea.Height * this.mapData.scale) - (base.Size.Height - MapData.toolbarHeight))) / ((float)this.m_HBarHeight)));
                        this.mapData.scale /= 1.2f;
                        this.mapData.resetGrid();
                        pMap.Refresh();
                    }
                }
            }
            else if (e.Delta > 0)
            {
                if (this.mapData.selItems.Count > 0)
                {
                    this.mapData.ReDoStack.Push(new OperElement("增大控件尺寸"));
                    this.mapData.toBigger();
                    pMap.Refresh();
                }
            }
            else if (this.mapData.selItems.Count > 0)
            {
                this.mapData.ReDoStack.Push(new OperElement("减小控件尺寸"));
                this.mapData.toSmaller();
                pMap.Refresh();
            }
            pMap.Refresh();
        }

        void pMap_Click(object sender, EventArgs e)
        {
            pMap.Focus();
        }

        void pMap_Resize(object sender, EventArgs e)
        {
            if (this.mapData == null) return;
            this.视图上的offset = new Point(0, 0);
            this.resetBarPos();
        }
        void pMap_MouseDown(object sender, MouseEventArgs e)
        {
            if (!e.Button.Equals(MouseButtons.Middle))
            {
                if (this.mapData.selItems.Count > 0)
                {
                    this.Cursor = Cursors.Hand;
                }
                Sharp sharp = this.mapData.getClickedItem(e.Location);
                if (!e.Button.Equals(MouseButtons.Right))
                {
                    if (null != sharp)
                    {
                        if ((Control.ModifierKeys != Keys.Control) && !sharp.isSel)
                        {
                            this.mapData.clearSel();
                        }
                        if (sharp.sharpType == "sbJYJ" && sharp.subType == "2")
                        {
                            this.mapData.addSel(sharp);
                        }
                    }
                    else
                    {
                        this.Cursor = Cursors.Default;
                        if (Control.ModifierKeys != Keys.Control)
                        {
                            this.mapData.clearSel();
                        }
                    }
                }
            }
        }
        
        void pMap_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                if (this.mapData.selItems.Count == 1)
                {
                    Sharp s = this.mapData.selItems.ToArray()[0];                    
                    if (s.sharpType == "sbJYJ" && s.subType == "2")
                    {
                        if (CGlobal.GroupDic.Keys.Contains(s.text))
                        {
                            CGlobal.CurDrawGroup = CGlobal.GroupDic[s.text];
                            foreach (Series ser in pChart.Series)
                            {
                                ser.Clear();
                            }
                            iCount = 0;
                            pChart.Axes.Left.SetMinMax(Math.Round(Math.Min(CGlobal.CurDrawGroup.sensor1.dblBase, CGlobal.CurDrawGroup.sensor2.dblBase), 0) - 3, Math.Round(Math.Max(CGlobal.CurDrawGroup.sensor1.dblBase, CGlobal.CurDrawGroup.sensor2.dblBase), 0) + 3);
                            pChart.Axes.Bottom.SetMinMax(0, 5000);
                            pChart.Invalidate();
                        }
                    }
                    CGlobal.CurShowGroup = new 传感器分组(CGlobal.CurDrawGroup);
                    propertyGrid1.SelectedObject = CGlobal.CurShowGroup;
                }
            }
            catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace+":"+ex.Message); }
        }

        void pMap_Paint(object sender, PaintEventArgs e)
        {
            this.g = e.Graphics;
            this.rePaint(e);
        }
       
        void CheckPenClick(object sender, EventArgs e)
        {
            if(mapData.allItems.Count ==0) return;
            ToolStripMenuItem _tsmi = sender as ToolStripMenuItem;
            if (_tsmi.Name == "m_Basic")
            {
                Sharp.set显示模式(true);
                mapData.初始化所有区段(CGlobal.BasicPen);
            }
            else if (_tsmi.Name == "m_White")
            {
                Sharp.set显示模式(false);
                mapData.初始化所有区段(CGlobal.WhiteBelt);
            }
            else if (_tsmi.Name == "m_Red")
            {
                Sharp.set显示模式(false);
                mapData.初始化所有区段(CGlobal.RedBelt);
            }
            else if (_tsmi.Name == "m_Negative")
            {
                Sharp.set显示模式(false);
                mapData.初始化所有区段(CGlobal.NegativePen);
            }
            this.Invalidate();
        }

        private void m_VBar_Scroll(object sender, ScrollEventArgs e)
        {
            this.Refresh();
        }
        
        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            if (this.mapData == null) return;
            this.视图上的offset = new Point(0, 0);
            this.resetBarPos();
        }

        public void rePaint(PaintEventArgs e)
        {
            if (mapData == null) return;
            this.mapData.resetOffset((float)((this.m_HBar.Value * 1.0) / ((double)this.m_VBarWidth)), (float)((this.m_VBar.Value * 1.0) / ((double)this.m_HBarHeight)), base.Size.Width - this.m_VBar.Width, base.Size.Height - this.m_HBar.Height);
            this.mapData.reDraw(e.Graphics);
            this.mapData.checkLine(this.g);
        }

        public void resetBarPos()
        {
            try
            {
                int minimum = (int)((((((double)((this.mapData.maxWorkArea.Width - this.mapData.ct.oraMapsize.Width) * this.mapData.scale)) / 2.0) - this.视图上的offset.X) / ((double)((this.mapData.maxWorkArea.Width * this.mapData.scale) - base.Size.Width))) * this.m_VBarWidth);
                int maximum = (int)((((((double)((this.mapData.maxWorkArea.Height - this.mapData.ct.oraMapsize.Height) * this.mapData.scale)) / 2.0) - this.视图上的offset.Y) / ((double)((this.mapData.maxWorkArea.Height * this.mapData.scale) - (base.Size.Height - this.toolStrip1.Height)))) * this.m_HBarHeight);
                if (minimum < this.m_HBar.Minimum)
                {
                    minimum = this.m_HBar.Minimum;
                }
                if (minimum > this.m_HBar.Maximum)
                {
                    minimum = this.m_HBar.Maximum;
                }
                if (maximum < this.m_VBar.Minimum)
                {
                    maximum = this.m_VBar.Minimum;
                }
                if (maximum > this.m_VBar.Maximum)
                {
                    maximum = this.m_VBar.Maximum;
                }
                this.m_HBar.Value = minimum;
                this.m_VBar.Value = minimum;

            }
            catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace + ":" + ex.Message); }
        }
                       
        protected override void OnClosing(CancelEventArgs e)
        {     
            IniFile file = new IniFile(Application.StartupPath + @"\platform.dat");
            file.Load();
            file.RemoveSection("RecentFile");
            foreach (CfgNode node in CfgManager.RootNode.GetSubNodeList())
            {
                if (!string.IsNullOrEmpty(node.NodeCfgFileName))
                    file.WriteString("RecentFile", node.NodeName, node.NodeCfgFileName);
            }
            file.Save();
            if (tDrawWavLens != null)
            {
                tDrawWavLens.Enabled = false;
            }
            base.OnClosing(e);
        }

        /***********************绘制波长图************************/
        private Graphics gtxt = null;
        private int iCount = 0;
        private System.Windows.Forms.Timer tDrawWavLens = null;
        private string strText = string.Empty;

        private void InitChart()
        {
            gtxt = pText.CreateGraphics();

            pChart.AutoRepaint = false;
            pChart.Series.Clear();
            for (int i = 0; i < 16; i++)
            {
                if (i % 3 == 0)
                {
                    this.AddSeries(pChart, Color.FromArgb((i * 16) & 0xFE, (i * 16 + 128) & 0xFE, (255 - i * 16) & 0xFE));
                }
                else if(i % 3 == 1)
                {
                    this.AddSeries(pChart, Color.FromArgb((i * 16 + 128) & 0xFE,  (255 - i * 16) & 0xFE,(i * 16) & 0xFE));
                }
                else if (i % 3 == 2)
                {
                    this.AddSeries(pChart, Color.FromArgb((255 - i * 16) & 0xFE, (i * 16) & 0xFE, (i * 16 + 128) & 0xFE));
                }
            }
            pChart.Axes.Bottom.Automatic = false;
            pChart.Axes.Bottom.SetMinMax(0, 5000);
            pChart.Axes.Left.Automatic = false;
            pChart.Axes.Left.SetMinMax(1525, 1570);
            pChart.AutoRepaint = true;
            pChart.Invalidate();
            tDrawWavLens = new System.Windows.Forms.Timer();
            tDrawWavLens.Interval = 50;
            tDrawWavLens.Tick += new EventHandler(tDrawWavLens_Tick);
            tDrawWavLens.Enabled = true;              
        }

        void tDrawWavLens_Tick(object sender, EventArgs e)
        {
            try
            {
                CSource.mutqwavsrc.WaitOne();
                if (CSource._queWavSource.Count == 0)
                {
                    CSource.mutqwavsrc.ReleaseMutex();
                    lblRecSrc.Text = string.Format("无光谱数据！");
                    return;
                }
                else 
                {
                    lblRecSrc.Text = string.Format("正在接收光谱数据！");
                }
                Queue<double[]>[] tmpQurry = CSource._queWavSource.ToArray();
                Queue<double[]>[] tmpArray = (Queue<double[]>[])tmpQurry.Clone();
                CSource._queWavSource.Clear();
                CSource.mutqwavsrc.ReleaseMutex();

                if (CGlobal.GroupDic.Count<1)
                {
                    return;
                }
                if (CGlobal.CurDrawGroup == null)
                {
                    CGlobal.CurDrawGroup = CGlobal.GroupDic.Values.ToArray()[0];
                    pChart.Axes.Left.SetMinMax(Math.Round(Math.Min(CGlobal.CurDrawGroup.sensor1.dblBase, CGlobal.CurDrawGroup.sensor2.dblBase), 0) - 3, Math.Round(Math.Max(CGlobal.CurDrawGroup.sensor1.dblBase, CGlobal.CurDrawGroup.sensor2.dblBase), 0) + 3);
                }
                if (tmpArray.Length == 0)
                {
                    return;
                }
                pChart.AutoRepaint = false;
                if (iCount + 5000 < 0)
                {
                    iCount = 0;
                    foreach (Series ser in pChart.Series)
                    {
                        ser.Clear();
                    }
                }
                //最后一包波长
                double[] latestdd=null;
                foreach (Queue<double[]> tmp in tmpArray)
                {
                    foreach (double[] dd in tmp)
                    {
                        latestdd = (double[])dd.Clone();

                        for (int i = 0; i < dd.Length; i++)
                        {
                            if (Math.Abs(CGlobal.CurDrawGroup.sensor1.dblBase - dd[i]) < 1.5d)
                            {
                                pChart.Series[i].Add(iCount, dd[i]);
                                CGlobal.CurDrawGroup.sensor1.dblReal = dd[i];
                            }
                            if (Math.Abs(CGlobal.CurDrawGroup.sensor2.dblBase - dd[i]) < 1.5d)
                            {
                                pChart.Series[i].Add(iCount, dd[i]);
                                CGlobal.CurDrawGroup.sensor2.dblReal = dd[i];
                            }
                        }
                        iCount++;
                    }
                }
                //修正显示数据
                /*
                int ipos = CGlobal.GroupDic[CGlobal.CurDrawGroup.text].iAxleNum % 32;
                if ( ipos>28)
                {
                    CGlobal.CurDrawGroup.iAxleNum = CGlobal.GroupDic[CGlobal.CurDrawGroup.text].iAxleNum + ipos;
                }
                else if (ipos < 4)
                {
                    CGlobal.CurDrawGroup.iAxleNum = CGlobal.GroupDic[CGlobal.CurDrawGroup.text].iAxleNum - ipos;
                }
                */
                //显示当前区段数据
                propertyGrid1.SelectedObject = new 传感器分组(CGlobal.CurDrawGroup);
                pChart.Header.Text = string.Format("计轴点{0}传感器实时曲线",CGlobal.CurDrawGroup.text);
                if (iCount > 5000)
                {
                    for (int i = 0; i < pChart.Series.Count; i++)
                    {
                        if (pChart.Series[i].Count > 5000)
                        {
                            pChart.Series[i].Delete(0, pChart.Series[i].Count - 5000);
                        }
                    }
                    pChart.Axes.Bottom.SetMinMax(iCount-5000,iCount);
                }
                pChart.AutoRepaint = true;
                pChart.Invalidate();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.StackTrace+":"+ex.Message);
            }
        }
        
        private void AddSeries(TChart tchart, Color lineColor)
        {
            FastLine fastline = new FastLine();
            fastline.Color = lineColor;
            fastline.LinePen.Width = 2;
            tchart.Series.Add(fastline);
        }
    }
}
